package com.binance.dynamodb.rule;

import java.util.Map;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.google.common.collect.Maps;

@Log4j2
public class DynamodbTableRuleSelector implements ApplicationContextAware {
    private static Map<String, DynamodbTableRule> dynamodbTableRuleMap = Maps.newHashMap();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(DynamodbTableRuleMapping.class);
        if (MapUtils.isEmpty(serviceBeanMap)) {
            return;
        }
        for (Object serviceBean : serviceBeanMap.values()) {
            DynamodbTableRuleMapping dynamodbTableRuleMapping =
                    serviceBean.getClass().getAnnotation(DynamodbTableRuleMapping.class);
            String tableName = dynamodbTableRuleMapping.tableName();
            dynamodbTableRuleMap.put(tableName, (DynamodbTableRule) serviceBean);
        }
    }

    public static Map<String, DynamodbTableRule> getDynamodbTableRuleMap() {
        return dynamodbTableRuleMap;
    }

    public static DynamodbTableRule getDefaultDynamodbTableRule() {
        return dynamodbTableRuleMap.get("Default");
    }

    public static String getTableNameByTableRule(String tableName, String env) {
        DynamodbTableRule dynamodbTableRule = dynamodbTableRuleMap.get(tableName);
        if (null == dynamodbTableRule) {
            dynamodbTableRule = getDefaultDynamodbTableRule();
        }
        return dynamodbTableRule.execute(tableName, env);
    }
}
